package com.wokeMy.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.BankAccountAndPayChannel;
import com.zhongcai.online.R;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.woke.adapter.OnItemClickListener;
import com.woke.data.Datas_bankedcard;
import com.woke.data.UnionPayChannel;
import com.woke.method.MyApp;
import com.wokeMy.view.adpter.PassAdapter;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.channe.hengfeng.HengfengRzActivity;
import com.wokeMy.view.channe.huixiang.HuixiangRZActivity;
import com.wokeMy.view.channe.huixiang.HuixiangzfActivity;
import com.wokeMy.view.channe.ronghui.RhKjzfActivity;
import com.wokeMy.view.channe.ronghui.RhuiRZhuActivity;
import com.wokeMy.view.channe.ronghui.RhuiZwmActivity;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class ZfbPassActivity extends BaseActivity implements View.OnClickListener{

    ListView passLv;
    PassAdapter passAdapter;

    TextView money_zfbPass_tv;
    OnItemClickListener  onItemClickListener;

    private float money;
    private MyApp application;
    private ArrayList<Datas_bankedcard> mBankedCards = new ArrayList<Datas_bankedcard> ();
    private LayoutInflater inflater;
    private ArrayList<UnionPayChannel> mUnionPayChannels = new ArrayList<>();

    Dialog dialog;
    String controller;
    int way;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_zfb_pass);
        //        EventBus.getDefault ().register (this);
    }

    @Override
    public void initActivity() {
        Log.e("initActivity",money+"");
        money_zfbPass_tv.setText("￥"+money);
        Log.e("initActivity",money_zfbPass_tv.getText()+"");
        passAdapter = new PassAdapter(getApplicationContext(),mUnionPayChannels);
        passAdapter.setOnItemClickListener(onItemClickListener);
        passLv.setAdapter(passAdapter);

    }

    @Override
    public void initView() {
        passLv=myFindViewById(R.id.select_zfbPass_lv);
        myFindViewById(R.id.zfbPass_image_back).setOnClickListener (this);
        money_zfbPass_tv = myFindViewById(R.id.money_zfbPass_tv);
        myFindViewById(R.id.zfbPass_text_title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(ZfbPassActivity.this,PassFlActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void initData() {
        Intent intent = getIntent ();
        money = intent.getFloatExtra ("money", 0.01f);
        application = (MyApp) getApplication ();
        final int userid = Integer.parseInt (application.getDatas_load ().getId ());
        inflater = getLayoutInflater ();
        dialog= Util.createLoadingDialog(ZfbPassActivity.this);
        myGetbanklistAndUnionPayChannel();
        getbanklistAndUnionPayChannel();
        onItemClickListener=new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, final int position) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!PassfastClick()) {
                            //回调快速点击
                            Log.e("mUnionlsway_id", mUnionPayChannels.toString());
                            way = mUnionPayChannels.get(position).getWay();
                            controller = mUnionPayChannels.get(position).getController();
                            UnionPayChannel unionPayChannel = mUnionPayChannels.get(position);
                            final Intent intent1 = new Intent();
                            Log.e("mUonPayChanstion)", "" + way);
                            if (money<unionPayChannel.getMinamount()){
                                aralogid("交易金额小于单笔最大额度");
                            }else if (money>unionPayChannel.getMaxamount()){
                                aralogid("交易金额大于单笔最大额度");
                            }else {
                                switch (way) {
                                    case 97:
                                    case 99:
                                    case 101:
                                    case 81:
                                        //富民 支付宝二维码
                                            intent1.setClass(ZfbPassActivity.this,
                                                    RhuiZwmActivity.class);
                                            intent1.putExtra("UnionPayChannel", unionPayChannel);
                                            intent1.putExtra("money", money);
                                            intent1.putExtra("flag", "fmZfbZwm");
                                            startActivity(intent1);
                                        break;
                                    case 83:
                                        //   恒丰银行 支付宝二维码
                                        intent1.setClass(ZfbPassActivity.this,
                                                HengfengRzActivity.class);
                                        intent1.putExtra("UnionPayChannel", unionPayChannel);
                                        intent1.putExtra("money", money);
                                        intent1.putExtra("flag", "fmZfbZwm");
                                        startActivity(intent1);
                                        break;
                                    case 103:
                                        //汇槽 支付宝充值接口
                                        OkGo.<String>post(Constant.HCZFBCZ_URL)//
                                                .tag(this)//
                                                .cacheMode(CacheMode.NO_CACHE)//
                                                .cacheKey("no_cache")   //对于无缓存模式,该参数无效
                                                .cacheTime(5000)        //对于无缓存模式,该时间无效
                                                .params("user_id",userid)//
                                                .params("way",way)
                                                .params("amount",money)
                                                .execute(new StringCallback() {
                                                    @Override
                                                    public void onSuccess(Response<String> response) {
                                                        JSONObject jsonObject = null;
                                                        try {
                                                            jsonObject = new JSONObject(response.body());
                                                            if (jsonObject.getString("flag").equals("success")){
                                                                String string = jsonObject.getJSONObject("data").getString("data");
                                                                Uri uri = Uri.parse(string);
                                                                Intent intent;
                                                                try {
                                                                    intent = Intent.parseUri(string,
                                                                            Intent.URI_INTENT_SCHEME);
                                                                    intent.addCategory("android.intent.category.BROWSABLE");
                                                                    intent.setComponent(null);
                                                                    startActivity(intent);
                                                                } catch (URISyntaxException e) {
                                                                    e.printStackTrace();
                                                                }

//                                                                intent1.setClass(ZfbPassActivity.this, HcZfbHtmlActivity.class);
//                                                                intent1.putExtra("html",string);
//                                                                startActivity(intent1);
                                                            }else {
                                                                tishi(jsonObject.getString("info"));
                                                            }

                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                        break;
                                    default:
                                        break;
                                }
                            }


                        }
                    }
                });
            }
            @Override
            public void OnItemClick(View view, Object object, int position) {

            }
        };
    }
    /**
     * //判断通道是否入驻
     */
    private void isChannelRz(String controller,final UnionPayChannel unionPayChannel) {
        if (application.getDatas_load () != null) {

            final int userid = Integer.parseInt (application.getDatas_load ().getId ());
            //            HttpMethods.getInstance ()
            //                    .getBankAccountAndUnionPayChannel (mAccountsAndChannelsObserver, userid, 1, 3);

            AsyncHttpClient ahc = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("user_id",userid);
            params.put("controller",controller);
            Log.e(" 判断通道是否入驻params",params.toString());
            //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
            ahc.post(Constant.ISPASSRZ_URL, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String result = null;
                    try {
                        result = new String(bytes, "utf-8");
                        //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("判断通道是否入驻", result);
                        try {
                            JSONObject jsonObject =new JSONObject(result);
                            int status=jsonObject.getJSONObject("data").getJSONObject("data").getInt("status");
                            final Intent intent2 = new Intent();
                            switch (way) {
                                case 75:
                                    //北京融汇
                                    Intent intent = new Intent();
                                    if (status==1){
                                        //已入住过 跳到融汇支付
                                        intent.setClass (ZfbPassActivity.this,
                                                RhKjzfActivity.class);
                                        intent.putExtra("UnionPayChannel",unionPayChannel);
                                        intent.putExtra ("money",money);
                                        startActivity (intent);
                                    }else {
                                        //未入住 跳到融汇入驻；
                                        intent.setClass (ZfbPassActivity.this,
                                                RhuiRZhuActivity.class);
                                        intent.putExtra("UnionPayChannel",unionPayChannel);
                                        intent.putExtra ("money",money);
                                        startActivity (intent);
                                    }
                                    break;
                                case 79:
                                    //融汇 银联二维码
                                    if (status==1){
                                        //已入住过 跳到融汇银联二维码
                                        intent2.setClass (ZfbPassActivity.this,
                                                RhuiZwmActivity.class);
                                        intent2.putExtra("UnionPayChannel",unionPayChannel);
                                        intent2.putExtra ("money",money);
                                        startActivity (intent2);
                                    }else {
                                        //未入住 跳到融汇入驻；
                                        intent2.setClass (ZfbPassActivity.this,
                                                RhuiRZhuActivity.class);
                                        intent2.putExtra("UnionPayChannel",unionPayChannel);
                                        intent2.putExtra ("money",money);
                                        startActivity (intent2);
                                    }
                                    break;
                                case 76:
                                    //汇享
                                    if (status==1){
                                        //已入住过 跳到汇享支付
                                        intent2.setClass (ZfbPassActivity.this,
                                                HuixiangzfActivity.class);
                                        intent2.putExtra("UnionPayChannel",unionPayChannel);
                                        intent2.putExtra ("money",money);
                                        startActivity (intent2);
                                    }else {
                                        //未入住 跳到汇享入驻；
                                        intent2.setClass (ZfbPassActivity.this,
                                                HuixiangRZActivity.class);
                                        intent2.putExtra("UnionPayChannel",unionPayChannel);
                                        intent2.putExtra ("money",money);
                                        startActivity (intent2);
                                    }
                                    break;

                                default:
                                    Toast.makeText(ZfbPassActivity.this,"该通道暂未开放，敬请期待",Toast.LENGTH_SHORT).show();
                                    break;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }
    /**
     * 获取支付宝对应的通道列表
     */
    private void myGetbanklistAndUnionPayChannel() {
        if (application.getDatas_load () != null) {

            int userid = Integer.parseInt (application.getDatas_load ().getId ());
            //            HttpMethods.getInstance ()
            //                    .getBankAccountAndUnionPayChannel (mAccountsAndChannelsObserver, userid, 1, 3);

            AsyncHttpClient ahc = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("userid",userid);
            params.put("type",1); //1.支付 2.收款（这里是支付
            params.put("kind",2); //1.微信 2.支付宝 3.银联（这里是）
            Log.e(" 获取支付宝对应的通道列表params",params.toString());
            //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
            ahc.post(Constant.BANKPASS_URL, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String result = null;
                    try {
                        result = new String(bytes, "utf-8");
                        //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("WO获取支付宝对应的通道列表", result);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }

    /**
     * 获取支付宝对应的通道列表
     */
    private void getbanklistAndUnionPayChannel() {
        if (application.getDatas_load () != null) {

            int userid = Integer.parseInt (application.getDatas_load ().getId ());
            HttpMethods.getInstance ()
                    .getBankAccountAndUnionPayChannel (mAccountsAndChannelsObserver, userid, 1, 2);//type 1--支付、2--收款   kind     1--微信、2--支付宝、3--银联
        }
    }

    private Observer<BankAccountAndPayChannel> mAccountsAndChannelsObserver = new Observer<BankAccountAndPayChannel> () {
        @Override
        public void onSubscribe(Disposable d) {
            //            Util.closeDialog(dialog);
        }

        @Override
        public void onNext(BankAccountAndPayChannel value) {
            if (value != null) {
                List<Datas_bankedcard> baList = value.getBanklist ();
                List<UnionPayChannel> clist = value.getGalllist ();
                if (baList != null && baList.size () > 0) {
                    mBankedCards.clear ();
                    mBankedCards.addAll (baList);
                }
                //                if (mBankedCards.size () > 0) {
                //                    if (showed == false) {
                //                        Datas_bankedcard data = mBankedCards.get (0);
                //                        mEcarno.setText (data.getCardno ());
                //                    } else {
                //                        Datas_bankedcard data = mBankedCards.get (mBankedCards.size () - 1);
                //                        mEcarno.setText (data.getCardno ());
                //                    }
                //
                //
                //
                //                }

                if (clist != null && clist.size () > 0) {
                    mUnionPayChannels.clear ();
                    mUnionPayChannels.addAll (clist);
                    if (passAdapter != null) {
                        passAdapter.notifyDataSetChanged ();
                    }
                }
                Util.closeDialog(dialog);

            }
        }

        @Override
        public void onError(Throwable e) {
            Util.closeDialog(dialog);
            Toast.makeText (ZfbPassActivity.this, e.getMessage (), Toast.LENGTH_SHORT)
                    .show ();
        }

        @Override
        public void onComplete() {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.zfbPass_image_back:
                finish ();
                break;
            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult (requestCode, resultCode, data);
        //        Log.e("onActivityResult","requestCode"+requestCode+"czhiortxian"+data.getStringExtra("czhiortxian"));
        Log.e("onActivityResult","requestCode"+requestCode);

        //        if (requestCode == 120 && resultCode == 97) {
        //            ArrayList<String> listnew = data.getStringArrayListExtra ("nocarpay");
        //            mEcarno.setText (listnew.get (2));
        //        }
    }

    AlertDialog alertDialog;

    private void aralogid( String kll) {
        alertDialog = new AlertDialog.Builder(ZfbPassActivity.this).
                setTitle("提示").
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }

}
